﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Admin_Grades : System.Web.UI.Page
{
    ILE_Global ileGlobal = new ILE_Global();
    ILE_Config ileConfig = new ILE_Config();

    protected int UserID
    {
        get
        {
            return (int)ViewState["UserID"];
        }
        set
        {
            ViewState["UserID"] = value;
        }
    }

    AssignmentsBLL assignmentsLogic = new AssignmentsBLL();
    StatisticsBLL statisticsLogic = new StatisticsBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Fill_ddlistClasses();
        }

        try
        {
            UsersBLL usersLogic = new UsersBLL();
            UserID = usersLogic.GetUserByUsername(HttpContext.Current.User.Identity.Name.ToString()).UserID;
            if (UserID == 0)
            {
                // *SteveMsg
                string _msg = "Your Session Information has ended. You have been logged out to prevent errors.";
                ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 2, "Default.aspx");
                return;
            }
        }
        catch (NullReferenceException ex)
        {
            ileGlobal.RecordError("Instructor.aspx.cs:Page_Load:001", ex, "User Session Ended Unexpectedly", 3, Request.Browser);
            FormsAuthentication.SignOut();
            // *SteveMsg
            string _msg = "Your Session Information has ended. You have been logged out to prevent errors.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 2, "Default.aspx");
            return;
        }
    }

    protected void Fill_ddlistClasses()
    {
        ClassBLL classLogic = new ClassBLL();
        Classes.CoursesDataTable courses = classLogic.GetCoursesOrderByTitle();

        ddlistClasses.Items.Clear();

        ListItem firstItem = new ListItem("--- Select Course ---", "0");
        ddlistClasses.Items.Add(firstItem);

        foreach (Classes.CoursesRow course in courses)
        {
            ListItem newItem = new ListItem(course.Title, course.CourseID.ToString());
            ddlistClasses.Items.Add(newItem);
        }
    }

    protected void ddlistClasses_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlistClasses.SelectedIndex != 0)
        {
            int courseID = Convert.ToInt32(ddlistClasses.SelectedValue);
            Fill_ddlistSections(courseID);
            PanelSection.Visible = true;
        }
        else
        {
            PanelSection.Visible = false;
        }

        ddlistSections.SelectedIndex = 0;
        PanelAssignments.Visible = false;
        PanelAssignmentGrades.Visible = false;
        PanelDetails.Visible = false;

        chkboxQuizShowQuestionStats.Checked = false;
        PanelQuizShowQuestionStats.Visible = false;

    }

    protected void Fill_ddlistSections(int CourseID)
    {
        ClassBLL classLogic = new ClassBLL();
        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, true);

        ddlistSections.Items.Clear();

        ListItem firstItem = new ListItem("--- Select Section ---", "0");
        ddlistSections.Items.Add(firstItem);

        foreach (Classes.Courses_SectionRow section in sections)
        {
            ListItem newItem = new ListItem(section.SectionNumber.ToString());
            ddlistSections.Items.Add(newItem);
        }
    }

    protected void ddlistSections_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (ddlistSections.SelectedIndex != 0)
        {
            string CourseID = ddlistClasses.SelectedValue;
            string SectionNumber = ddlistSections.SelectedValue;
            Session["CourseID"] = CourseID;
            Session["SectionNumber"] = SectionNumber;

            ObjectDataSourceAssignments.DataBind();
            GridViewAssignments.DataBind();
            GridViewAssignments.SelectedIndex = -1;
            PanelAssignments.Visible = true;
            PanelAssignmentGrades.Visible = false;
            PanelDetails.Visible = false;
            chkboxQuizShowQuestionStats.Checked = false;
            PanelQuizShowQuestionStats.Visible = false;
        }
        else
        {
            PanelAssignments.Visible = false;
        }
    }

    protected void GridViewAssignments_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (((GridView)sender).SelectedIndex != -1)
        {
            int AssignmentID = Convert.ToInt32(((GridView)sender).SelectedValue);

            if (assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID).AssignmentType == "Quiz")
            {
                ObjectDataSourceQuizGrades.DataBind();
                GridViewQuizGrades.DataBind();
                getQuizGradeAverages();
                PanelQuizAssignment.Visible = true;
                PanelEssayAssignment.Visible = false;
                GridViewQuizGrades.Visible = true;
            }
            else
            {
                ObjectDataSourceEssayGrades.DataBind();
                GridViewEssayGrades.DataBind();
                PanelEssayAssignment.Visible = true;
                PanelQuizAssignment.Visible = false;
                GridViewQuizGrades.Visible = true;
            }

            PanelAssignmentGrades.Visible = true;
            PanelDetails.Visible = false;
        }
    }

    protected void rdobtnsAssignmentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        filterAssignments();
    }

    protected void rdobtnsAssignmentStandard_SelectedIndexChanged(object sender, EventArgs e)
    {
        filterAssignments();
    }

    protected void rdobtnsAssignmentDue_SelectedIndexChanged(object sender, EventArgs e)
    {
        filterAssignments();
    }

    private void filterAssignments()
    {
        ObjectDataSourceAssignments.DataBind();
        GridViewAssignments.DataBind();
        GridViewAssignments.SelectedIndex = -1;
        PanelAssignments.Visible = true;
        PanelAssignmentGrades.Visible = false;
        chkboxQuizShowQuestionStats.Checked = false;
        PanelQuizShowQuestionStats.Visible = false;
        PanelDetails.Visible = false;
    }


    #region Quiz Grades

    protected void chkboxQuizShowQuestionStats_CheckedChanged(object sender, EventArgs e)
    {
        if (chkboxQuizShowQuestionStats.Checked)
        {
            LoadQuizQuestionStats();
            PanelQuizShowQuestionStats.Visible = true;
        }
        else
        {
            PanelQuizShowQuestionStats.Visible = false;
        }
    }

    protected void LoadQuizQuestionStats()
    {
        Assignments.Assignments_QuizRow quizAssignment = assignmentsLogic.GetAssignmentQuizByAssignmentID(Convert.ToInt32(GridViewAssignments.SelectedValue));
        XDocument xDocQuizAssignmentFiltered = XDocument.Parse(quizAssignment.QuizAssignment);

        xDocQuizAssignmentFiltered.Descendants("question").Where(
            el => (string)el.Attribute("excluded").Value == "true").Remove();

        XmlDataSourceQuizQuestionStats.EnableCaching = false;
        XmlDataSourceQuizQuestionStats.Data = xDocQuizAssignmentFiltered.ToString();
        XmlDataSourceQuizQuestionStats.DataBind();

        RepeaterQuizQuestionsStats.DataBind();
    }

    protected void rdobtnsQuizFilter_SelectedIndexChanged(object sender, EventArgs e)
    {
        filterQuizGrades();
    }

    private void filterQuizGrades()
    {
        ObjectDataSourceQuizGrades.DataBind();
        GridViewQuizGrades.DataBind();
        GridViewQuizGrades.SelectedIndex = -1;

        getQuizGradeAverages();

        PanelDetails.Visible = false;
    }

    private void getQuizGradeAverages()
    {
        decimal totalPoints = 0;

        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        int CourseID = Convert.ToInt32(ddlistClasses.SelectedValue);
        int SectionNumber = Convert.ToInt32(ddlistSections.SelectedValue);

        Assignments.Assignments_Submission_QuizDataTable quizSubmissions = 
            submissionsLogic.GetQuizSubmissionsByAssignmentIdAndCourseIdAndSectionNumberAndFilter(AssignmentID, CourseID, SectionNumber, rdobtnsQuizFilter.SelectedValue);


        foreach (Assignments.Assignments_Submission_QuizRow quizSubmission in quizSubmissions)
        {
            totalPoints += quizSubmission.GradePercentage;
        }

        if (quizSubmissions.Count == 0)
        {
            lblQuizGradeAverage.Text = "Not Available.";
            return;
        }

        decimal Average = totalPoints / quizSubmissions.Count;

        lblQuizGradeAverage.Text = (Average / 100).ToString("P");
    }

    protected void GridViewQuizGrades_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView gridView = ((GridView)sender);

        if (gridView.SelectedIndex != -1)
        {
            int QuizSubmissionID = Convert.ToInt32(gridView.SelectedValue);

            AssignmentsSubmissionsBLL assignmentSubmissionsLogic = new AssignmentsSubmissionsBLL();

            Assignments.Assignments_Submission_QuizRow quizSubmission = assignmentSubmissionsLogic.GetQuizSubmission(QuizSubmissionID);

            XmlDataSourceQuizSubmission.EnableCaching = false;
            XmlDataSourceQuizSubmission.Data = quizSubmission.StudentAnswers;
            XmlDataSourceQuizSubmission.DataBind();

            RepeaterQuizStudentSubmission.DataBind();

            PanelDetails.Visible = true;
            PanelEssaySubmissionDetails.Visible = false;
            PanelQuizSubmissionDetails.Visible = true;
        }
        else
        {
            PanelDetails.Visible = false;
        }
    }

    protected int GetQuestionStats(int LearnObjID, int QuestionID, bool IsAnsweredCorrectly)
    {
        int result = statisticsLogic.CountByLearnObjIdAndQuestionId(LearnObjID, QuestionID, IsAnsweredCorrectly);

        if (IsAnsweredCorrectly == false && result == 0)
        {
            return 0;
        }
        else
        {
            return result;
        }
    }

    protected int GetClassSectionQuestionStats(int LearnObjID, int QuestionID, int CourseID, int SectionNumber, bool IsAnsweredCorrectly)
    {
        int result = statisticsLogic.CountByLearnObjIdAndQuestionIdAndCourseIdAndSectionNumber(LearnObjID, QuestionID, CourseID, SectionNumber, IsAnsweredCorrectly);

        if (IsAnsweredCorrectly == false && result == 0)
        {
            return 0;
        }
        else
        {
            return result;
        }
    }

    protected double GetQuestionStatsPercentage(int LearnObjID, int QuestionID)
    {
        int correct = statisticsLogic.CountByLearnObjIdAndQuestionId(LearnObjID, QuestionID, true);
        int incorrect = statisticsLogic.CountByLearnObjIdAndQuestionId(LearnObjID, QuestionID, false);

        if ((incorrect + correct) == 0)
        {
            return 0;
        }
        else
        {
            return (double)correct / ((double)incorrect + correct);
        }
    }
    protected double GetClassSectionQuestionStatsPercentage(int LearnObjID, int QuestionID, int CourseID, int SectionNumber)
    {
        int correct = statisticsLogic.CountByLearnObjIdAndQuestionIdAndCourseIdAndSectionNumber(LearnObjID, QuestionID, CourseID, SectionNumber, true);
        int incorrect = statisticsLogic.CountByLearnObjIdAndQuestionIdAndCourseIdAndSectionNumber(LearnObjID, QuestionID, CourseID, SectionNumber, false);

        if ((incorrect + correct) == 0)
        {
            return 0;
        }
        else
        {
            return (double)correct / ((double)incorrect + correct);
        }
    }

    /// <summary>
    /// This function is referenced from
    /// http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp2_dc11032006003657AM/exportxl_asp2_dc.aspx?ArticleID=000c64fb-8a22-414a-8247-984335aaa0eb
    /// </summary>
    protected void btnQuizGradesExportToExcel_Click(object sender, EventArgs e)
    {
        ExportQuizGradeToExcel();
    }

    /// <summary>
    /// This function is referenced from
    /// http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp2_dc11032006003657AM/exportxl_asp2_dc.aspx?ArticleID=000c64fb-8a22-414a-8247-984335aaa0eb
    /// http://aspsnippets.com/post/2009/03/14/Export-GridView-To-WordExcelPDFCSV-in-ASPNet.aspx
    /// </summary>
    private void ExportQuizGradeToExcel()
    {
        ClassBLL classLogic = new ClassBLL();
        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        int CourseID = Convert.ToInt32(ddlistClasses.SelectedValue);
        int SectionNumber = Convert.ToInt32(ddlistSections.SelectedValue);

        string fileName = "Quiz Grade - " + classLogic.GetCourse(CourseID).Title.Trim() + " - Sect#" + SectionNumber.ToString() +
            " - " + assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID).AssignmentTitle + ".xls";

        string quizGrades = "attachment;filename=\"" + fileName + "\"";

        GridViewQuizGrades.Columns[0].Visible = false;

        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition", quizGrades);
        Response.ContentType = "application/ms-excel";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        GridViewQuizGrades.AllowSorting = false;
        GridViewQuizGrades.AllowPaging = false;
        GridViewQuizGrades.GridLines = GridLines.Both;
        GridViewQuizGrades.DataBind();

        //Change the Header Row back to white color
        GridViewQuizGrades.HeaderRow.Style.Add("background-color", "#FFFFFF");


        //Apply style to Individual Cells
        for (int i = 1; i <= 6; i++)
        {
            GridViewQuizGrades.HeaderRow.Cells[i].Style.Add("background-color", "#5D7B9D");
            GridViewQuizGrades.HeaderRow.Cells[i].Style.Add("font-weight", "Bold");
            GridViewQuizGrades.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");
            GridViewQuizGrades.HeaderRow.Cells[i].Style.Add("height", "25px");
        }

        for (int i = 0; i < GridViewQuizGrades.Rows.Count; i++)
        {
            GridViewRow row = GridViewQuizGrades.Rows[i];

            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;

            //Apply text style to each Row
            //row.Attributes.Add("class", "textmode");

            //Apply style to Alternating Row
            if (i % 2 != 0)
            {
                for (int j = 1; j <= 6; j++)
                {
                    row.Cells[j].Style.Add("background-color", "#DDDDDD");
                }
            }

            row.Cells[1].Attributes.Add("class", "textmode");
            row.Cells[2].Attributes.Add("class", "textmode");
            row.Cells[3].Attributes.Add("class", "textmode");
            row.Cells[4].Attributes.Add("class", "textmode");
            row.Cells[5].Attributes.Add("class", "percentmode");
            row.Cells[6].Attributes.Add("class", "datetimemode");
        }

        // This line was causing some error and That's why this page's 'EnabledEventValidation' property set to "False"
        GridViewQuizGrades.RenderControl(htmlWrite);

        //style to format numbers to string
        string style = "<style> .textmode { mso-number-format:\\@; } .percentmode { mso-number-format: Percent; } .datetimemode { mso-number-format: \" mm\\/dd\\/yyyy hh:mm:ss AM\\/PM\" } </style>";
        Response.Write(style);
        Response.Output.Write(stringWrite.ToString());
        Response.Flush();
        Response.End();

        GridViewQuizGrades.Columns[0].Visible = true;
    }

    /// <summary>
    /// This function is referenced from
    /// http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp2_dc11032006003657AM/exportxl_asp2_dc.aspx?ArticleID=000c64fb-8a22-414a-8247-984335aaa0eb
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
    }

    protected void btnSendAllQuizGrades_Click(object sender, EventArgs e)
    {
        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        int CourseID = Convert.ToInt32(Session["CourseID"]);
        int SectionNumber = Convert.ToInt32(Session["SectionNumber"]);
        string Filter = rdobtnsQuizFilter.SelectedValue;

        Assignments.Assignments_Submission_QuizDataTable quizGrades = submissionsLogic.GetQuizSubmissionsByAssignmentIdAndCourseIdAndSectionNumber(AssignmentID, CourseID, SectionNumber);

        if (quizGrades.Count == 0)
        {
            // *SteveMsg
            string _msg = "No quiz submission has been found.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);
        ClassBLL classLogic = new ClassBLL();
        Classes.CoursesRow course = classLogic.GetCourse(CourseID);
        string emailSubject = "[ILE] Your results for " + assignment.AssignmentTitle;

        string emailBody = "Below are your quiz results for<br />";

        emailBody += "<div style='margin-left: 20px; font-size: large;'>" + course.Title.ToString() + " | Section " + SectionNumber.ToString() + "</div>";
        emailBody += "<br /><br /><b>Quiz Name : " + assignment.AssignmentTitle.ToString() + "</b><br /><br />";

        string emailBodyTop = emailBody;

        {
            UsersBLL usersLogic = new UsersBLL();
            int _userid = quizGrades[0].UserID;

            Assignments.Assignments_Submission_QuizDataTable gradesByUser = new Assignments.Assignments_Submission_QuizDataTable();

            for (int i = 0; quizGrades.Count >= i; i++)
            {
                Assignments.Assignments_Submission_QuizRow quizGrade = null;

                if (quizGrades.Count == i)
                {
                    quizGrade = quizGrades[i - 1];
                    _userid = 0;
                }
                else
                {
                    quizGrade = quizGrades[i];

                }

                if (_userid == quizGrade.UserID)
                {
                    try
                    {
                        gradesByUser.ImportRow(quizGrade);
                    }
                    catch
                    { }
                }
                else
                {
                    Users.UsersRow _user = usersLogic.GetUserByUserID(quizGrade.UserID);
                    emailBody += _user.FirstName + " " + _user.LastName + "<br />";
                    emailBody += _user.Email + "<br /><br />";

                    // To get the highest grades of all attempts.
                    {
                        List<decimal> grades = new List<decimal>();

                        foreach (Assignments.Assignments_Submission_QuizRow grade in gradesByUser)
                        {
                            try
                            {
                                grades.Add(grade.GradePercentage);
                            }
                            catch
                            {
                                // Just skip!
                            }
                        }

                        decimal highestGrade = 0;
                        foreach (decimal _grade in grades)
                        {
                            if (_grade > highestGrade)
                                highestGrade = _grade;
                        }
                        emailBody += "<span style='font-size: large;'>Your Grade for this Quiz : " + highestGrade.ToString() + "%</span>";

                        if (highestGrade >= 90)
                        {
                            emailBody += "<br /><div style='width: 100%; text-align: center; font-weight: bold; font-size: large; color: #00933b;'>Excellent!</div>";
                        }

                        emailBody += "<br /><hr /><br />";
                    }

                    emailBody += "Below you will find the results for the quiz. If you have taken the quiz more than once results for each attempt are listed below.<br /><br /><br />";

                    foreach (Assignments.Assignments_Submission_QuizRow grade in gradesByUser)
                    {
                        emailBody += "Quiz results attempt <b>" + grade.Attempts.ToString() + "</b>:<br />";

                        XDocument xDocQuizSubmission = new XDocument();
                        xDocQuizSubmission = XDocument.Parse(grade.StudentAnswers.ToString());

                        List<XElement> _questions = xDocQuizSubmission.Descendants("question").ToList();

                        int questionNumber = 1;
                        foreach (XElement question in _questions)
                        {
                            emailBody += "<u><b>Question #" + questionNumber.ToString() + "</b></u><br /><br />";
                            emailBody += "<div style='margin-left: 20px;'>";
                            emailBody += question.Element("questiontext").Value.ToString() + "<br /><br />";

                            emailBody += "<ul>";

                            bool isQuestionAnsweredCorrectly = true;
                            List<XElement> _choices = question.Descendants("choice").ToList();
                            foreach (XElement choice in _choices)
                            {
                                emailBody += "<li>" + choice.Value;

                                if (Convert.ToBoolean(choice.Attribute("iscorrectanswer").Value) == true)
                                {
                                    emailBody += " <i>(Correct Answer)</i>";
                                }

                                if (Convert.ToBoolean(choice.Attribute("isstudentanswer").Value) == true)
                                {
                                    emailBody += " <i>(Your Answer)</i>";
                                }
                                emailBody += "</li>";

                                if (Convert.ToBoolean(choice.Attribute("iscorrectanswer").Value) != true)
                                {
                                    if (Convert.ToBoolean(choice.Attribute("isstudentanswer").Value) == true)
                                    {
                                        isQuestionAnsweredCorrectly = false;
                                    }
                                }
                                else
                                {
                                    if (Convert.ToBoolean(choice.Attribute("isstudentanswer").Value) != true)
                                    {
                                        isQuestionAnsweredCorrectly = false;
                                    }
                                }
                            }
                            emailBody += "</ul>";

                            if (isQuestionAnsweredCorrectly == true)
                            {
                                emailBody += "<i>Did you answer this correclty?: <span style='font-weight: bold; color: #00933b;'>Yes</span></i><br /><br />";
                            }
                            else
                            {
                                emailBody += "<i>Did you answer this correclty?: <span style='font-weight: bold; color: #ff0000;'>No</span></i><br /><br />";
                            }

                            emailBody += "</div>";

                            questionNumber++;
                        }

                        try
                        {
                            emailBody += "<b>Grade : </b>" + grade.GradePercentage.ToString() + "%<br /><br />";
                        }
                        catch
                        {
                            // Nothing
                        }
                        emailBody += "<hr /><br />";
                    }

                    emailBody += "<br /><b>Note:</b> Please do not reply to this email. Replies to this email will not be responded to or read. If you have questions or comments, contact your instructor or the librarian working with your course.";

                    System.Net.Mail.MailAddressCollection receivers = new System.Net.Mail.MailAddressCollection();
                    Users.UsersRow user = usersLogic.GetUserByUserID(quizGrade.UserID);
                    receivers.Add(user.Email);
                    bool result = ileGlobal.SendEmail(receivers, ileConfig.getDefaultEmailSenderAddress().Address.ToString(), emailSubject, emailBody);
                    if (result)
                    {
                        _userid = quizGrade.UserID;
                        gradesByUser.Clear();
                        emailBody = emailBodyTop;
                    }
                    else
                    {
                        // *SteveMsg
                        string _msg = "Error sending emails";
                        ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                        return;
                    }
                }
            }
        }

        // *SteveMsg
        string _msg2 = "Successfully emailed quiz grades to all students.";
        ModalPopupMessage.ShowModalPopup("ILE Message", _msg2, 1);
    }

    protected void btnSendQuizGrade_Click(object sender, EventArgs e)
    {
        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        int CourseID = Convert.ToInt32(Session["CourseID"]);
        int SectionNumber = Convert.ToInt32(Session["SectionNumber"]);
        int QuizSubmissionID = Convert.ToInt32(GridViewQuizGrades.SelectedValue);
        string Filter = rdobtnsQuizFilter.SelectedValue;

        int _userID = submissionsLogic.GetQuizSubmission(QuizSubmissionID).UserID;


        Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);
        ClassBLL classLogic = new ClassBLL();
        Classes.CoursesRow course = classLogic.GetCourse(CourseID);
        string emailSubject = "[ILE] Your results for " + assignment.AssignmentTitle;

        string emailBody = "Below are your quiz results for<br />";

        emailBody += "<div style='margin-left: 20px; font-size: large;'>" + course.Title.ToString() + " | Section " + SectionNumber.ToString() + "</div>";
        emailBody += "<br /><br /><b>Quiz Name : " + assignment.AssignmentTitle.ToString() + "</b><br /><br />";

        Assignments.Assignments_Submission_QuizDataTable quizSubmissions = submissionsLogic.GetQuizSubmissionsByAssignmentIdAndCourseIdAndSectionNumberAndUserID(AssignmentID, CourseID, SectionNumber, _userID);

        UsersBLL usersLogic = new UsersBLL();
        Users.UsersRow _user = usersLogic.GetUserByUserID(quizSubmissions[0].UserID);
        emailBody += _user.FirstName + " " + _user.LastName + "<br />";
        emailBody += _user.Email + "<br /><br />";

        List<decimal> grades = new List<decimal>();

        foreach (Assignments.Assignments_Submission_QuizRow submission in quizSubmissions)
        {
            //XDocument xDocQuizSubmission = new XDocument();
            //xDocQuizSubmission = XDocument.Parse(submission.StudentAnswers.ToString());
            //grades.Add(Convert.ToDecimal(xDocQuizSubmission.Element("quizsubmission").Element("grade").Element("percentage").Value.ToString()));
            grades.Add(submission.GradePercentage);
        }

        decimal highestGrade = 0;
        foreach (decimal _grade in grades)
        {
            if (_grade > highestGrade)
                highestGrade = _grade;
        }
        emailBody += "<span style='font-size: large;'>Your Grade for this Quiz : " + highestGrade.ToString() + "%</span>";

        if (highestGrade >= 90)
        {
            emailBody += "<br /><div style='width: 100%; text-align: center; font-weight: bold; font-size: large; color: #00933b;'>Excellent!</div>";
        }

        emailBody += "<br /><hr /><br />";

        emailBody += "Below you will find the results for the quiz. If you have taken the quiz more than once results for each attempt are listed below.<br /><br /><br />";

        foreach (Assignments.Assignments_Submission_QuizRow submission in quizSubmissions)
        {
            emailBody += "Quiz results attempt <b>" + submission.Attempts.ToString() + "</b>:<br />";

            XDocument xDocQuizSubmission = new XDocument();
            xDocQuizSubmission = XDocument.Parse(submission.StudentAnswers.ToString());

            List<XElement> _questions = xDocQuizSubmission.Descendants("question").ToList();

            int questionNumber = 1;
            foreach (XElement question in _questions)
            {
                emailBody += "<u><b>Question #" + questionNumber.ToString() + "</b></u><br /><br />";
                emailBody += "<div style='margin-left: 20px;'>";
                emailBody += question.Element("questiontext").Value.ToString() + "<br /><br />";

                emailBody += "<ul>";

                bool isQuestionAnsweredCorrectly = true;
                List<XElement> _choices = question.Descendants("choice").ToList();
                foreach (XElement choice in _choices)
                {
                    emailBody += "<li>" + choice.Value;

                    if (Convert.ToBoolean(choice.Attribute("iscorrectanswer").Value) == true)
                    {
                        emailBody += " <i>(Correct Answer)</i>";
                    }

                    if (Convert.ToBoolean(choice.Attribute("isstudentanswer").Value) == true)
                    {
                        emailBody += " <i>(Your Answer)</i>";
                    }
                    emailBody += "</li>";

                    if (Convert.ToBoolean(choice.Attribute("iscorrectanswer").Value) != true)
                    {
                        if (Convert.ToBoolean(choice.Attribute("isstudentanswer").Value) == true)
                        {
                            isQuestionAnsweredCorrectly = false;
                        }
                    }
                    else
                    {
                        if (Convert.ToBoolean(choice.Attribute("isstudentanswer").Value) != true)
                        {
                            isQuestionAnsweredCorrectly = false;
                        }
                    }
                }
                emailBody += "</ul>";

                if (isQuestionAnsweredCorrectly == true)
                {
                    emailBody += "<i>Did you answer this correclty?: <span style='font-weight: bold; color: #00933b;'>Yes</span></i><br /><br />";
                }
                else
                {
                    emailBody += "<i>Did you answer this correclty?: <span style='font-weight: bold; color: #ff0000;'>No</span></i><br /><br />";
                }

                emailBody += "</div>";

                questionNumber++;
            }

            emailBody += "<b>Grade : </b>" + submission.GradePercentage.ToString() + "%<br /><br />";
            emailBody += "<hr /><br />";
        }

        emailBody += "<br /><b>Note:</b> Please do not reply to this email. Replies to this email will not be responded to or read. If you have questions or comments, contact your instructor or the librarian working with your course.";

        System.Net.Mail.MailAddressCollection receivers = new System.Net.Mail.MailAddressCollection();
        receivers.Add(_user.Email);
        bool result = ileGlobal.SendEmail(receivers, ileConfig.getDefaultEmailSenderAddress().Address.ToString(), emailSubject, emailBody);
        if (result)
        {
            // *SteveMsg
            string _msg2 = "Successfully emailed quiz grade to the student.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg2, 1);
        }
        else
        {
            // *SteveMsg
            string _msg = "Error sending emails";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }
    }

    #endregion


    #region Essay Grades

    protected void rdobtnsEssayFilter_SelectedIndexChanged(object sender, EventArgs e)
    {
        filterEssayGrades();
    }

    private void filterEssayGrades()
    {
        ObjectDataSourceEssayGrades.DataBind();
        GridViewEssayGrades.DataBind();
        GridViewEssayGrades.SelectedIndex = -1;

        PanelDetails.Visible = false;
    }

    protected void GridViewEssayGrades_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView gridView = ((GridView)sender);

        if (gridView.SelectedIndex != -1)
        {
            int EssaySubmissionID = Convert.ToInt32(gridView.SelectedValue);

            Session.Add("EssaySubmissionID", EssaySubmissionID);

            AssignmentsSubmissionsBLL assignmentSubmissionsLogic = new AssignmentsSubmissionsBLL();
            Assignments.Assignments_Submission_EssayRow essaySubmission = assignmentSubmissionsLogic.GetEssaySubmission(EssaySubmissionID);

            if (essaySubmission.StudentAnswer == null || essaySubmission.StudentAnswer == String.Empty)
            {
                // *SteveMsg
                lblStudentEssaySubmission.Text = "<div style='min-width: 500px; text-align: center;'><i>Student has not submitted an essay.</i></div>";
            }
            else
            {
                lblStudentEssaySubmission.Text = essaySubmission.StudentAnswer;
            }

            if (essaySubmission.Grade == String.Empty)
            {
                txtEssayGrade.Text = String.Empty;
            }
            else
            {
                txtEssayGrade.Text = essaySubmission.Grade;
            }

            try
            {
                Assignments.Assignments_Submission_Essay_CommentsRow comment =
                    submissionsLogic.GetEssaySubmissionCommentsByEssaySubmissionID(EssaySubmissionID)[0];

                EditorEssayComment.Content = comment.Comment;
            }
            catch
            { }

            PanelDetails.Visible = true;
            PanelQuizSubmissionDetails.Visible = false;
            PanelEssaySubmissionDetails.Visible = true;
        }
        else
        {
            PanelDetails.Visible = false;
        }
    }

    protected void chkboxViewEssayQuestion_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox checkBox = ((CheckBox)sender);
        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);

        if (checkBox.Checked)
        {
            lblEssayQuestion.Text = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID).Instruction;
            PanelEssaySubmissionDetailsQuestion.Visible = true;
        }
        else
            PanelEssaySubmissionDetailsQuestion.Visible = false;
    }

    protected void chkboxEssaySubmissionComments_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox checkBox = ((CheckBox)sender);
        LoadEssaySubmissionComments(checkBox);
    }

    private void LoadEssaySubmissionComments(CheckBox checkBox)
    {
        int EssaySubmissionID = Convert.ToInt32(Session["EssaySubmissionID"]);

        if (checkBox.Checked)
        {
            Assignments.Assignments_Submission_Essay_CommentsDataTable comments =
                submissionsLogic.GetEssaySubmissionCommentsByEssaySubmissionID(EssaySubmissionID);

            RepeaterEssayComments.DataSource = comments.Rows;
            RepeaterEssayComments.DataBind();
            PanelEssaySubmissionComments.Visible = true;
        }
        else
            PanelEssaySubmissionComments.Visible = false;
    }

    AssignmentsSubmissionsBLL submissionsLogic = new AssignmentsSubmissionsBLL();

    protected void btnSubmitGrade_Click(object sender, EventArgs e)
    {
        int EssaySubmissionID = Convert.ToInt32(Session["EssaySubmissionID"]);
        string Grade = txtEssayGrade.Text;

        bool result = submissionsLogic.UpdateEssaySubmissionGrade(Grade, EssaySubmissionID);

        if (result)
        {
            // *SteveMsg
            string _msg = "The Essay has been graded.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
            GridViewEssayGrades.DataBind();
        }
        else
        {
            // *SteveMsg
            string _msg = "Failed to submit the grade. Please try again";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
        }
    }

    protected void btnEssaySubmitComment_Click(object sender, EventArgs e)
    {
        int EssaySubmissionID = Convert.ToInt32(Session["EssaySubmissionID"]);
        string Comment = EditorEssayComment.Content.ToString();

        bool isDuplicated = submissionsLogic.IsEssaySubmissionCommentDuplicated(EssaySubmissionID, UserID);

        if (isDuplicated)
        {
            bool result = submissionsLogic.UpdateEssaySubmissionComment(Comment, EssaySubmissionID, UserID);
            if (result)
            {
                // *SteveMsg
                string _msg = "Essay comment has been updated.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
                LoadEssaySubmissionComments(chkboxEssaySubmissionComments);
            }
            else
            {
                // *SteveMsg
                string _msg = "Failed to update essay comment";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
            }
        }
        else
        {
            bool result = submissionsLogic.InsertEssaySubmissionComment(EssaySubmissionID, UserID, Comment);

            if (result)
            {
                // *SteveMsg
                string _msg = "Essay comment has been submitted.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
                LoadEssaySubmissionComments(chkboxEssaySubmissionComments);
            }
            else
            {
                // *SteveMsg
                string _msg = "Failed to submit essay comment";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
            }
        }
    }

    protected void RepeaterEssayComments_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Assignments.Assignments_Submission_Essay_CommentsRow row = e.Item.DataItem as Assignments.Assignments_Submission_Essay_CommentsRow;

            Label lblInstructor = e.Item.FindControl("lblInstructor") as Label;
            Label lblComment = e.Item.FindControl("lblComment") as Label;
            Label lblCommentDateTime = e.Item.FindControl("lblCommentDateTime") as Label;

            UsersBLL usersLogic = new UsersBLL();

            Users.UsersRow user = usersLogic.GetUserByUserID(row.InstructorUserID);

            lblInstructor.Text = user.FirstName + " " + user.LastName;
            lblComment.Text = row.Comment;
            lblCommentDateTime.Text = row.TimeStamp.ToString("f");
        }
    }

    protected void btnEssayGradesExportToExcel_Click(object sender, EventArgs e)
    {
        ClassBLL classLogic = new ClassBLL();
        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        int CourseID = Convert.ToInt32(ddlistClasses.SelectedValue);
        int SectionNumber = Convert.ToInt32(ddlistSections.SelectedValue);

        string fileName = "Essay Grade - " + classLogic.GetCourse(CourseID).Title.Trim() + " - Sect#" + SectionNumber.ToString() +
            " - " + assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID).AssignmentTitle + ".xls";

        string essayGrades = "attachment;filename=\"" + fileName + "\"";

        Response.Clear();
        Response.Buffer = true;

        GridViewEssayGrades.Columns[0].Visible = false;
        GridViewEssayGrades.Columns[6].Visible = false;

        Response.AddHeader("content-disposition", essayGrades);
        Response.ContentType = "application/ms-excel";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        GridViewEssayGrades.AllowSorting = false;
        GridViewEssayGrades.AllowPaging = false;
        GridViewEssayGrades.GridLines = GridLines.Both;
        GridViewEssayGrades.DataBind();

        //Change the Header Row back to white color
        GridViewEssayGrades.HeaderRow.Style.Add("background-color", "#FFFFFF");


        //Apply style to Individual Cells
        for (int i = 1; i <= 7; i++)
        {
            GridViewEssayGrades.HeaderRow.Cells[i].Style.Add("background-color", "#5D7B9D");
            GridViewEssayGrades.HeaderRow.Cells[i].Style.Add("font-weight", "Bold");
            GridViewEssayGrades.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");
            GridViewEssayGrades.HeaderRow.Cells[i].Style.Add("height", "25px");
        }

        for (int i = 0; i < GridViewEssayGrades.Rows.Count; i++)
        {
            GridViewRow row = GridViewEssayGrades.Rows[i];

            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;

            //Apply style to Alternating Row
            if (i % 2 != 0)
            {
                for (int j = 1; j <= 7; j++)
                {
                    row.Cells[j].Style.Add("background-color", "#DDDDDD");
                }
            }

            row.Cells[1].Attributes.Add("class", "textmode");
            row.Cells[2].Attributes.Add("class", "textmode");
            row.Cells[3].Attributes.Add("class", "textmode");
            row.Cells[4].Attributes.Add("class", "textmode");
            row.Cells[5].Attributes.Add("class", "textmode");
            row.Cells[6].Attributes.Add("class", "textmode");
            row.Cells[7].Attributes.Add("class", "datetimemode");
        }

        // This line was causing some error and That's why this page's 'EnabledEventValidation' property set to "False"
        GridViewEssayGrades.RenderControl(htmlWrite);

        //style to format numbers to string
        string style = "<style> .textmode { mso-number-format:\\@; } .percentmode { mso-number-format: Percent; } .datetimemode { mso-number-format: \" mm\\/dd\\/yyyy hh:mm:ss AM\\/PM\" } </style>";
        Response.Write(style);
        Response.Output.Write(stringWrite.ToString());
        Response.Flush();
        Response.End();

        GridViewEssayGrades.Columns[0].Visible = true;
        GridViewEssayGrades.Columns[6].Visible = true;
    }

    protected void btnSendAllEssayGrades_Click(object sender, EventArgs e)
    {
        // SEND ONLY GRADED ONES
        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        int CourseID = Convert.ToInt32(Session["CourseID"]);
        int SectionNumber = Convert.ToInt32(Session["SectionNumber"]);
        string Filter = rdobtnsEssayFilter.SelectedValue;

        Assignments.Assignments_Submission_EssayDataTable essayGrades =
            submissionsLogic.GetEssaySubmissionsByAssignmentIdAndCourseIdAndSectionNumberAndFilter(AssignmentID, CourseID, SectionNumber, Filter);

        if (essayGrades.Count == 0)
        {
            // *SteveMsg
            string _msg = "No essay submissions have been found.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);
        ClassBLL classLogic = new ClassBLL();
        Classes.CoursesRow course = classLogic.GetCourse(CourseID);
        string emailSubject = "[ILE] Your Essay Grade for " + assignment.AssignmentTitle;

        string emailBody = "This message has been generated by ILE at the request of your instructor.<br /><br />Essay feedback for<br />";

        emailBody += "<div style='margin-left: 20px; font-size: large;'>" + assignment.AssignmentTitle.ToString() + " | Section " + SectionNumber.ToString() + "</div>";
        emailBody += "<br /><br /><b>Assignment Name : <br /><div style='margin-left: 20px; font-size: medium;'>" + assignment.AssignmentTitle.ToString() + "</b></div><br /><br />";

        emailBody += "<h3>Essay Prompt</h3>";
        emailBody += "<div style='margin-left: 20px; padding: 10px;'>";
        emailBody += assignment.Instruction.ToString();
        emailBody += "</div><br />";


        string emailBodyTop = emailBody;

        {
            UsersBLL usersLogic = new UsersBLL();
            int _userid = essayGrades[0].UserID;

            Assignments.Assignments_Submission_EssayDataTable gradesByUser = new Assignments.Assignments_Submission_EssayDataTable();

            for (int i = 0; essayGrades.Count >= i; i++)
            {
                Assignments.Assignments_Submission_EssayRow essayGrade = null;

                if (essayGrades.Count == i)
                {
                    essayGrade = essayGrades[i - 1];
                    _userid = 0;
                }
                else
                {
                    essayGrade = essayGrades[i];
                }

                if (_userid == essayGrade.UserID)
                {
                    try
                    {
                        gradesByUser.ImportRow(essayGrade);
                    }
                    catch
                    { }
                }
                else
                {

                    Users.UsersRow _user = usersLogic.GetUserByUserID(essayGrade.UserID);
                    //emailBody += _user.FirstName + " " + _user.LastName + "<br />";
                    //emailBody += _user.Email + "<br /><br />";

                    emailBody += "<h3>Submission for " + _user.FirstName + " " + _user.LastName + " <span style='font-size: smaller;'>(" + _user.Email + ")</span></h3>";
                    emailBody += "<div style='margin-left: 20px; padding: 10px;'>";
                    emailBody += essayGrade.StudentAnswer.ToString();
                    emailBody += "</div>";

                    emailBody += "<br /><hr /><br />";

                    Assignments.Assignments_Submission_Essay_CommentsDataTable comments =
                        submissionsLogic.GetEssaySubmissionCommentsByEssaySubmissionID(essayGrade.EssaySubmissionID);

                    if (comments.Count != 0)
                    {
                        emailBody += "<h3>Comment from Instructor(s)</h3>";
                        emailBody += "<div style='margin-left: 20px;'>";
                        emailBody += "<table>";
                        foreach (Assignments.Assignments_Submission_Essay_CommentsRow comment in comments)
                        {
                            Users.UsersRow instructor = usersLogic.GetUserByUserID(comment.InstructorUserID);

                            emailBody += "<tr>";
                            emailBody += "<td style='vertical-align: top;'>" + "<u>" + instructor.FirstName + " " + instructor.LastName + " : </u></td>";
                            emailBody += "<td style='vertical-align: top;'>" + comment.Comment + "<br /><span style='font-size: smaller;'>- Commented on " + comment.TimeStamp.ToString("f") + "</span>";
                            emailBody += "</tr>";
                        }
                        emailBody += "</table>";
                        emailBody += "</div>";
                    }

                    if (!essayGrade.IsGradeNull())
                    {
                        emailBody += "<br /><br />Your Essay Grade : <b>" + essayGrade.Grade.ToString() + "</b>";
                    }

                    emailBody += "<br /><br /><b>Note:</b> Please do not reply to this email. Replies to this email will not be responded to or read. If you have questions or comments, contact your instructor or the librarian working with your course.";

                    System.Net.Mail.MailAddressCollection receivers = new System.Net.Mail.MailAddressCollection();
                    Users.UsersRow user = usersLogic.GetUserByUserID(essayGrade.UserID);
                    receivers.Add(user.Email);
                    bool result = ileGlobal.SendEmail(receivers, ileConfig.getDefaultEmailSenderAddress().Address.ToString(), emailSubject, emailBody);
                    if (result)
                    {
                        // *SteveMsg
                        string _msg = "Successfully emailed essay grades and comments to all students.";
                        ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
                        _userid = user.UserID;
                        emailBody = emailBodyTop;
                    }
                    else
                    {
                        // *SteveMsg
                        string _msg = "Error sending emails";
                        ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                        return;
                    }
                }
            }
        }
    }

    protected void btnSendEssayGrade_Click(object sender, EventArgs e)
    {
        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        int CourseID = Convert.ToInt32(Session["CourseID"]);
        int SectionNumber = Convert.ToInt32(Session["SectionNumber"]);
        string Filter = rdobtnsEssayFilter.SelectedValue;

        int EssaySubmissionID = Convert.ToInt32(GridViewEssayGrades.SelectedValue);

        Assignments.Assignments_Submission_EssayRow essaySubmission = submissionsLogic.GetEssaySubmission(EssaySubmissionID);

        int _userID = submissionsLogic.GetEssaySubmission(EssaySubmissionID).UserID;

        Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);
        ClassBLL classLogic = new ClassBLL();
        Classes.CoursesRow course = classLogic.GetCourse(CourseID);
        string emailSubject = "[ILE] Your Essay Grade for " + assignment.AssignmentTitle;

        string emailBody = "This message has been generated by ILE at the request of your instructor.<br /><br />Essay feedback for<br />";

        emailBody += "<div style='margin-left: 20px; font-size: large;'>" + assignment.AssignmentTitle.ToString() + " | Section " + SectionNumber.ToString() + "</div>";
        emailBody += "<br /><br /><b>Assignment Name : <br /><div style='margin-left: 20px; font-size: medium;'>" + assignment.AssignmentTitle.ToString() + "</b></div><br /><br />";

        emailBody += "<h3>Essay Prompt</h3>";
        emailBody += "<div style='margin-left: 20px; border: solid 1px #999;'>";
        emailBody += assignment.Instruction.ToString();
        emailBody += "</div><br />";

        UsersBLL usersLogic = new UsersBLL();

        Users.UsersRow _user = usersLogic.GetUserByUserID(_userID);

        emailBody += "<h3>Submission for " + _user.FirstName + " " + _user.LastName + " <span style='font-size: smaller;'>(" + _user.Email + ")</span></h3>";
        emailBody += "<div style='margin-left: 20px; border: solid 1px #999;'>";
        emailBody += essaySubmission.StudentAnswer.ToString();
        emailBody += "</div>";

        emailBody += "<br /><hr /><br />";


        Assignments.Assignments_Submission_Essay_CommentsDataTable comments =
            submissionsLogic.GetEssaySubmissionCommentsByEssaySubmissionID(EssaySubmissionID);

        if (comments.Count != 0)
        {
            emailBody += "<h3>Comment from Instructor(s)</h3>";
            emailBody += "<div style='margin-left: 20px;'>";
            emailBody += "<table>";
            foreach (Assignments.Assignments_Submission_Essay_CommentsRow comment in comments)
            {
                Users.UsersRow instructor = usersLogic.GetUserByUserID(comment.InstructorUserID);

                emailBody += "<tr>";
                emailBody += "<td style='vertical-align: top;'>" + "<u>" + instructor.FirstName + " " + instructor.LastName + " : </u></td>";
                emailBody += "<td style='vertical-align: top;'>" + comment.Comment + "<br /><span style='font-size: smaller;'>- Commented on " + comment.TimeStamp.ToString("f") + "</span>";
                emailBody += "</tr>";
            }
            emailBody += "</table>";
            emailBody += "</div>";
        }

        if (!essaySubmission.IsGradeNull())
        {
            emailBody += "<br /><br />Your Essay Grade : <b>" + essaySubmission.Grade.ToString() + "</b>";
        }

        emailBody += "<br /><b>Note:</b> Please do not reply to this email. Replies to this email will not be responded to or read. If you have questions or comments, contact your instructor or the librarian working with your course.";

        System.Net.Mail.MailAddressCollection receivers = new System.Net.Mail.MailAddressCollection();
        Users.UsersRow user = usersLogic.GetUserByUserID(_userID);
        receivers.Add(user.Email);
        bool result = ileGlobal.SendEmail(receivers, ileConfig.getDefaultEmailSenderAddress().Address.ToString(), emailSubject, emailBody);
        if (result)
        {
            // *SteveMsg
            string _msg = "Successfully emailed essay grade and comments to student.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
        }
        else
        {
            // *SteveMsg
            string _msg = "Error sending emails";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }
    }
    #endregion
}